package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

type Login struct {
	User     string `json:"userName"`
	Password string `json:"userPassword"`
}

// 对传入json进行处理
func jsonTest(c *gin.Context) {
	var jsonObj Login
	err := c.ShouldBindJSON(&jsonObj)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	if jsonObj.User != "root" || jsonObj.Password != "admin" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "账号或密码错误",
		})
	}
	//都通过就返回结果
	c.JSON(http.StatusOK, gin.H{
		"status": "200,登录成功",
	})

}

// 对表单处理
func formTest(c *gin.Context) {
	types := c.DefaultPostForm("type", "post")
	userName := c.PostForm("userName")
	userPassword := c.PostForm("userPassword")
	if userName != "root" || userPassword != "admin" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "账号密码错误",
		})
		return
	}

	c.JSON(http.StatusOK, fmt.Sprintf("username:%s,password:%s,type:%s", userName, userPassword, types))
}

func main() {
	r := gin.Default()
	v1 := r.Group("/v1")
	{
		//对传入json进行测试
		v1.POST("loginJson", jsonTest)
		v1.POST("loginForm", formTest)
	}

	r.Run(":8080")

}
